#include"db_row.h"

using namespace std;

namespace uhdpbs {
	namespace db {
		row::row(string_string_map originals, table* tbl) {
			ptblContainer = tbl;
			bIsDeleted = false;
			
			mChanges = string_string_map();
			mOriginals = originals;
		}
		row::~row() {}

		table* row::get_table() { return ptblContainer; }

		string row::get_id() { return get_value(string("id")); }
		void row::set_id(string val) { set_value(string("id"), val); }

		string row::get_value(string col) {
			string_string_iterator itOriginals = mOriginals.find(col);
			string_string_iterator itChanges = mChanges.find(col);
			if(itChanges != mChanges.end())
				return itChanges->second;
			else if(itOriginals != mOriginals.end())
				return itOriginals->second;
			else
				return string("");
		}
		std::string row::trim(std::string orig) {
			if(orig.length() == 0)
				return orig;			
			
			bool bStop = false;
			int iStart = 0;
			for(int cnt = 0; cnt < orig.length() && bStop == false; cnt++) {
				char c = orig[cnt];
				if(!isspace(c)) {
					bStop = true;
					iStart = cnt;
				}
			}

			bStop = false;
			int iEnd = 0;
			for(int cnt = orig.length() - 1; cnt >= 0 && bStop == false; cnt--) {
				char c = orig[cnt];
				if(!isspace(c)) {
					bStop = true;
					iEnd = cnt;
				}
			}

			return orig.substr(iStart, iEnd - iStart + 1);
		}
		void row::set_value(string col, string val) {
			string sTrimmed = trim(val);
			
			bool bInOriginals = mOriginals.find(col) != mOriginals.end();
			bool bSameAsOriginals = false;
			if(bInOriginals)
				bSameAsOriginals = mOriginals[col] == sTrimmed;
			else
				bSameAsOriginals = sTrimmed.length() == 0;

			bool bInChanges = mChanges.find(col) != mChanges.end();
			bool bSameAsChanges = false;
			if(bInOriginals)
				bSameAsChanges = mChanges[col] == sTrimmed;


			if(bSameAsOriginals && bInChanges) {
				mChanges.erase(col);
				return;
			} else if(!bSameAsOriginals && !bSameAsChanges && sTrimmed.length() > 0) {
				mChanges[col] = sTrimmed;
			}
		}

		string_string_map row::get_originals() { return mOriginals; }
		string_string_map row::get_changes() { return mChanges; }

		bool row::is_deleted() { return bIsDeleted; }
		void row::is_deleted(bool val) { bIsDeleted = val; }

		bool row::is_new() { 
			if(this->mOriginals.size() == 0)
				return true;

			return false;
		}

		void row::reset() {
			this->mChanges.clear();
		}

	}
}
